package cn.edu.sjtu.process_status_data.model;

import cn.edu.sjtu.process_status_data.util.ModelUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class StatusMap {

    private static Map<Integer, JSONObject> map = new HashMap<>();

    @PostConstruct
    private void initData() {
        Resource resource = new ClassPathResource("static/data.json");
        try {
            String areaData = IOUtils.toString(resource.getInputStream(), Charset.forName("UTF-8"));
            JSONObject parse = (JSONObject) JSONObject.parse(areaData);
            map = JSONObject.toJavaObject(parse, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private JSONObject getInstances(Integer num) {
        JSONObject jsonObject = map.get(num);
        return (JSONObject) jsonObject.get("instances");
    }

    public String getName(Integer num) {
        JSONObject jsonObject = map.get(num);
        return jsonObject.getObject("name", String.class);
    }

    public Status getStatus(Integer num, Integer instance) {
        JSONObject instances = getInstances(num);
        return instances.getObject(String.valueOf(instance), Status.class);
    }

    public long getExpectedTime(Integer num) {
        JSONObject jsonObject = map.get(num);
        return jsonObject.getObject("expectedTime", Long.class) * 60000;
    }

    public void statusChange(Integer num, Integer instance, Status status) {
        JSONObject instances = getInstances(num);
        instances.replace(String.valueOf(instance), status);
    }

    public List<Object> getProcessData(Integer num, Integer instance) {
        JSONObject instances = getInstances(num);
        Status status = instances.getObject(String.valueOf(instance), Status.class);
        if (Status.busy.equals(status)) {
            if (num == 1 || num == 3) {
                return ModelUtil.spinningData(Math.random());
            }
            //扩展其他工序数据
        }else if(Status.done.equals(status)){
            if(num == 0){
                return ModelUtil.blankData();
            }else if(num == 2 || num == 4){
                return ModelUtil.examineData();
            }
            //扩展其他工序数据
        }
        return null;
    }
}
